import java.io.*;
import java.net.*;
import java.util.*;
import java.security.Security;
import java.security.Provider;
import javax.net.ssl.*;
import local.util.MyPrint;
import java.text.DecimalFormat;

import local.util.MyStringFormat;

public class SectorApp {
    
    private static boolean debug = false;
    private static boolean save  = false;
    private Calendar calendar = Calendar.getInstance();

    private String myUrl = null;
    private String urlReturnString = new String();
    private Vector urlReturnVector = new Vector(10);
    private Vector recordVector    = new Vector(10);
    private String symb;
    private static String sectorId;
    private static Hashtable profileHashTable   = new Hashtable();
    private static Hashtable tickHashTable = new Hashtable();
    private String queryString = new String ("");
    private Vector newTickVector = new Vector ();

    DecimalFormat td = new DecimalFormat("0.00");
    MyStringFormat mf = new MyStringFormat();

    private void printHelpMessage () {

     MyPrint.printLine("=",100);
     System.out.print("[1][Start Price][End Price][Volume Low Limite][Volume Up Limite]");
     System.out.println("[Number Of Results][Ex]");
     System.out.println("[2][SAVE]");
	
     MyPrint.printLine("=",100);
     System.exit(0);
    }

    public static void main (String args[]) {

	SectorApp down_and_up = new SectorApp ();

	if (!(args.length == 7 || args.length == 2)) {
	    down_and_up.printHelpMessage();
	}

	String url_return_string       = null;
	Vector url_return_vector1      = new Vector(10);
	Vector url_return_vector2      = new Vector(10);
	Vector record_vector_up        = new Vector(10);
	Vector record_vector_down      = new Vector(10);

	GroupProfileLoader loader = new GroupProfileLoader();
	loader.setFileName("./Data/Sector/Sector.txt");
	loader.loadProfile();
	profileHashTable = loader.getHashTable();

	String choice = null;
	String start_price = null;
	String end_price   = null;
	String v_low_limit     = null;
	String v_up_limit     = null;
	String numb_results = null;
	String exchange = "0"; //[All=0] [Nasdaq=15]
	boolean chart   = false ;
	String sector_id = null;
	String sector_name = null;

	choice       = args[0];

	if (choice.equals("1")) {
	    start_price   = args[1];
	    end_price     = args[2];
	    v_low_limit   = args[3];
	    v_up_limit    = args[4];
	    numb_results  = args[5];
	    exchange      = args[6];
	}
	else if (choice.equals("2")) {
	    start_price    = "1";
	    end_price      = "1000";
	    v_low_limit    = "100";
	    v_up_limit     = "1000000000000";
	    numb_results   = "5000";
	    exchange       = "15";

	    if (args[1].equals("SAVE")) {
		save  = true;
	    }
	}

	down_and_up.setUrl("https://www.bigcharts.com/custom/datek-com/screener/screener.asp?"+
			   "sh=1%2C1%2C1%2C1%2C1%2C1%2C1&pg=vop&cols=0&cols=4&cols=8&cols=1&"+
			   "cols=5&cols=9&cols=2&cols=6&cols=10&cols=3&cols=7&sort=4&sortd=0&"+
			   "numresults="+numb_results+"&s1=1&s1p1="+start_price+"&s1p2="+
			   end_price+"&s2=1&"+
			   "s2p1=0&s2p2=0.01&s2p3=0&s4p2=0&s9=1&s9p1="+v_low_limit+
			   "&s9p2="+v_up_limit+"&exchange="+exchange+"&result.x=45&result.y=15");

	System.out.print("Up Connecting ....");
	down_and_up.connectToUrl();
	System.out.println("Down");

	System.out.print("Up Geting Url return string....");
	url_return_string  = down_and_up.getUrlReturnString();
	System.out.println("Down");

	System.out.print("Up Putting String into Vector....");
	down_and_up.stringToVector(url_return_string);
	System.out.println("Down");

	System.out.print("Up Geting Return Vector.....");
	url_return_vector1  = down_and_up.getUrlReturnVector();
	System.out.println("Down");

	System.out.print("Up Selecting Useful Elements from Vector...");
	url_return_vector1  = down_and_up.selectUsefulInfo (url_return_vector1);
	System.out.println("Down");

       
	VectorCheck vc1 = new VectorCheck ();
	vc1.checkUrlReturnVector (url_return_vector1);
	//MyPrint.printVector(url_return_vector1,1);
	url_return_vector1 = vc1.getRecordVector();
	//MyPrint.printVector(url_return_vector1,1);
	System.out.print("Up Setting Record.....");
	down_and_up.setRecord(url_return_vector1);
	System.out.println("Down");

	System.out.print("Up Getting Record.....");
	record_vector_up   = down_and_up.getRecordVector();
	System.out.println("Down");

	Enumeration test = record_vector_up.elements();
	while (test.hasMoreElements() && debug) {
	    down_and_up.printRecord((StockRecord)test.nextElement());
	}


	down_and_up.setUrl("https://www.bigcharts.com/custom/datek-com/screener/screener.asp?"+
			   "sh=1%2C1%2C1%2C1%2C1%2C1%2C1&pg=vop&cols=0&cols=4&cols=8&cols=1&"+
			   "cols=5&cols=9&cols=2&cols=6&cols=10&cols=3&cols=7&sort=4&sortd=1&"+
			   "numresults="+numb_results+"&s1=1&s1p1="+start_price+"&s1p2="+
			   end_price+"&s2=1&"+
			   "s2p1=1&s2p2=0.01&s2p3=0&s4p2=0&s9=1&s9p1="+v_low_limit+
			   "&s9p2="+v_up_limit+"&exchange="+exchange+"&result.x=45&result.y=11");

	down_and_up.connectToUrl();
	System.out.println("Down Connecting ....");
	url_return_string = down_and_up.getUrlReturnString();
	System.out.println("Down Geting Url return string....");
	down_and_up.stringToVector(url_return_string);
	System.out.println("Down Putting String into Vector....");
	url_return_vector2 = down_and_up.getUrlReturnVector();
	System.out.println("Down Geting Return Vector.....");
	url_return_vector2 = down_and_up.selectUsefulInfo (url_return_vector2);
	System.out.println("Down Selecting Useful Elements from Vector...");

       
	VectorCheck vc2 = new VectorCheck ();
	vc2.checkUrlReturnVector (url_return_vector2);
	url_return_vector2 = vc2.getRecordVector();

	down_and_up.setRecord(url_return_vector2);
	System.out.println("Down Setting Record.....");

	record_vector_down = down_and_up.getRecordVector();
	System.out.println("Down Getting Record.....");

	System.out.println("Up Sort Record.....");

	record_vector_up   = down_and_up.sortRecordVector(record_vector_up);
	System.out.println("Down Sort Record.....\n\n");

	record_vector_down = down_and_up.sortRecordVector(record_vector_down);

	System.out.println("Start printing Sector Record.....");

	down_and_up.sumSectorTotal(record_vector_up , record_vector_down);

	System.out.println("End printing Sector Record");

	MyPrint.printVector(down_and_up.newTickVector,1);
    }

 

    public void setUrl (String url) {
	if (debug) System.out.println("Url:"+url);
	myUrl = url;
    }

    private void connectToUrl () {
	String url_return_string = "";
	URL url ;

	HttpsURLConnection httpsConnection = null;

	try {            
	    url = new URL (myUrl); 
	    //if (debug) System.out.println(myUrl); 
	    try {                
		httpsConnection = (HttpsURLConnection)url.openConnection();                
		httpsConnection.setDoOutput(false);                
		httpsConnection.connect();                

		if (debug) {
		    System.out.println("Connection Code and Message:" + 
				   httpsConnection.getResponseCode() + 
				   " - " + httpsConnection.getResponseMessage()+"\n");
		}

		BufferedReader in = new BufferedReader(new InputStreamReader
		    (httpsConnection.getInputStream()));

		StringBuffer buff1= new StringBuffer("");

		url_return_string = in.readLine();

		while (url_return_string != null) {
		    buff1.append(url_return_string);
		    url_return_string = in.readLine();
		}

		in.close();            

		url_return_string = buff1.toString();
		url_return_string = url_return_string.replaceAll("\n","");
		url_return_string = url_return_string.replaceAll("\t","");
		url_return_string = url_return_string.replaceAll("&nbsp;","");
		url_return_string = url_return_string.replaceAll(">",">\n");
		url_return_string = url_return_string.replaceAll("</","\n</");
		//System.out.println("URL RETURN Sturn String:"+url_return_string); 
		setUrlReturnString(url_return_string);
	    } catch (IOException ioe) {                
		System.out.println(ioe.getMessage());  
		System.exit(1);            
	    }        
	} catch (MalformedURLException mue) {            
	     System.out.println(mue.getMessage());            
	    System.exit(1);        
	} catch (Exception e) {            
	    e.printStackTrace();            
	    System.exit(1);        
	}    
    }

    public String getUrlReturnString () {
	return urlReturnString;
    }

    private void setUrlReturnString (String urlReturnSr) {
	urlReturnString = urlReturnSr;
    }

    private void setRecord (Vector v) {

	String temp [] = {"","","","","","","","","","",""};
	Vector record_vector = new Vector ();

	String sector_id = null;
	String sector_name = null;
	String industry_id = null;
	String industry_name = null;
	Hashtable sector_id_h = new Hashtable();
	Hashtable sector_name_h = new Hashtable();
	Hashtable industry_id_h = new Hashtable();
	Hashtable industry_name_h = new Hashtable();

	DataBaseQuery db1 = new DataBaseQuery ();

	String db_qr_str = null;
	db_qr_str = "SELECT * FROM tick";

	db1.setTickTableHashtable(db_qr_str, "Tick","Sector_Id");
	sector_id_h = db1.getTickTableHashtable();

	DataBaseQuery db2 = new DataBaseQuery ();

	db_qr_str = "SELECT * FROM tick";

	db2.setTickTableHashtable(db_qr_str, "Tick", "Sector_Name");
	sector_name_h = db2.getTickTableHashtable();

	DataBaseQuery db3 = new DataBaseQuery ();

	db_qr_str = "SELECT * FROM tick";

	db3.setTickTableHashtable(db_qr_str, "Tick", "Industry_Id");
	industry_id_h = db3.getTickTableHashtable();

	DataBaseQuery db4 = new DataBaseQuery ();

	db_qr_str = "SELECT * FROM tick";

	db4.setTickTableHashtable(db_qr_str, "Tick", "Industry_Name");
	industry_name_h = db4.getTickTableHashtable();

	Enumeration penum = v.elements();
	while ( penum.hasMoreElements()) {
	    Vector rv = new Vector ();
	    rv  = (Vector)penum.nextElement();

	    int m = 0;
	    Enumeration penum1 = rv.elements();
	    while ( penum1.hasMoreElements()) {
		temp[m] =  (String)penum1.nextElement();
		m++;
	    }

	    StockRecord record = new StockRecord ();

	    if (temp[0].equals("Symbol")) {
		sector_id     = "Sector ID";
		sector_name   = "Sector Name";
		industry_id   = "Industry ID";
		industry_name = "Industry Name";
	    }
	    else {
		sector_id     = (String)sector_id_h.get(temp[0]);
		sector_name   = (String)sector_name_h.get(temp[0]);
		industry_id   = (String)industry_id_h.get(temp[0]);
		industry_name = (String)industry_name_h.get(temp[0]);

		if (sector_name == null || sector_id == null) {
		    System.out.println("**********Can not find Tick:"+temp[0]+" In database!*********");
		    
		    if (!newTickVector.contains(temp[0])) {
			newTickVector.addElement(temp[0]);
		    }

		    sector_id   = "130";
		    sector_name = "Unknow";
		    industry_id   = "130";
		    industry_name = "Unknow";
		}
		else {
		    if (debug){
			System.out.println("sector_id="+sector_id);
			System.out.println("sector_name="+sector_name);
		    }
		}
	    }

	    record.setTick    (temp[0]);
	    record.setName    (temp[1]);
	    record.setPrice   (temp[2]);
	    record.setChange  (temp[3]);
	    record.setPercent (temp[4]);
	    record.setVolume  (temp[5]);
	    record.setTime    (temp[6]);	
	    record.setHigh    (temp[7]);
	    record.setLow     (temp[8]);
	    record.setPeratio (temp[9]);
	    record.setMarkCap (temp[10]);
	    record.setSectorId  (sector_id);
	    record.setSectorName(sector_name);
	    record.setIndustryId  (industry_id);
	    record.setIndustryName(industry_name);

	    record_vector.addElement(record);

	}

	setRecordVector(record_vector);
    }

    public Vector getRecordVector() {
	return (recordVector);
    }

    public void setRecordVector(Vector v) {
	recordVector = v;
    }

    private void stringToVector (String input) {
	Vector url_return_vector = new Vector ();
	String element = "";
	StringTokenizer tokens = new StringTokenizer(input, "\n");
	while (tokens.hasMoreTokens()) {
	    element = tokens.nextToken();
	    url_return_vector.addElement(element);
	}

	setUrlReturnVector(url_return_vector);
    }

    public Vector getUrlReturnVector() {
	return urlReturnVector;
    }

    public void setUrlReturnVector(Vector v) {
	urlReturnVector = v;
    }

    private Vector selectUsefulInfo (Vector v_in) {
	Vector v_out = new Vector (10);
	String text = "";
	Enumeration penum = v_in.elements();
       
	while ( penum.hasMoreElements()) {

	    text = (String)penum.nextElement();
	    if (text.startsWith("<FONT FACE=\"Arial,Helvetica,sans-serif")) {
		//System.out.println(text);
		break;
	    }
	}
	
	while ( penum.hasMoreElements() ) {
	    text = (String)penum.nextElement();
	    if (text.startsWith("Previous")) {
		break;
	    }
	   
	    
	    if ( !(text.startsWith("<") || text.startsWith("+") || 
		   text.startsWith("to<") )) {
		v_out.addElement(text);
	    }
	}
	
	return v_out;
    }

    private void insertIntoDataBase( Vector inputV) {

	StringBuffer queryBf = new StringBuffer("INSERT INTO sector_record VALUES (");


	int m =0; int n = 0; String temp;  double change=0.00;
	Enumeration penum = inputV.elements();

	while ( penum.hasMoreElements()) {
	    m++; 
	    temp = (String)penum.nextElement();
	    //System.out.print(temp+"\t");

	    if (m%8==0 && m != 0)  System.out.println();

	    if (m >8) {

	       temp = temp.replaceAll("%","");
	       temp = temp.replaceAll(",","");
	       temp = temp.replaceAll("UNCH","0");
	       temp = temp.replaceAll("n/a","0");

	       queryBf.append("'"+temp+"',");

	       if (m%8==0) {
		   queryBf.append("'"+sectorId.trim()+"','"+profileHashTable.get(sectorId)+"'"+");");
		   //System.out.println(queryBf.toString());
		   DataBaseInsert myInsert = new DataBaseInsert();	
		   myInsert.setQueryString(queryBf.toString());

		   if(myInsert.insertData() == 1) {
		       queryBf = new StringBuffer("INSERT INTO sector_record VALUES (");
		   }
		   else {
		       do {
			   myInsert.setQueryString(queryBf.toString());
		       } while (myInsert.insertData()!=1);

		       queryBf = new StringBuffer("INSERT INTO sector_record VALUES (");
		   }
	       }
	    }

	}
    }    

    private Vector sortRecordVector(Vector inputV) {

	int total = 0;
	Vector out_v = new Vector ();
	StockRecord record = new StockRecord ();
	StockRecord temp_record = new StockRecord ();

	Enumeration enum1 = inputV.elements();
	while ( enum1.hasMoreElements()) {
	    record = (StockRecord)enum1.nextElement();

	    Enumeration enum2 = inputV.elements();
	    while ( enum2.hasMoreElements()) {
		temp_record = (StockRecord)enum2.nextElement();
		if ((temp_record.getSectorName()).equals(record.getSectorName())){
		    if (!out_v.contains(temp_record)) {
			out_v.addElement(temp_record);
		    }
		}		
	    }
	}

	return out_v;
    }

    private void printRecord(Vector inputV1, Vector inputV2) {

	int total_up   = 0;
	int total_down = 0;
	Vector out_v   = new Vector ();
	StockRecord record1     = new StockRecord ();
	StockRecord record2     = new StockRecord ();
	StockRecord temp_record = new StockRecord ();

	Enumeration enum1 = inputV1.elements();
	while ( enum1.hasMoreElements()) {
	    record1 = (StockRecord)enum1.nextElement();

	    if ((record1.getTick()).equals("Symbol")) {
		printRecord(record1);
		MyPrint.printLine("=",100);
		continue;
	    }

	    Enumeration enum2 = inputV1.elements();
	    while ( enum2.hasMoreElements()) {
		temp_record = (StockRecord)enum2.nextElement();
		if ((temp_record.getSectorName()).equals(record1.getSectorName())){

		    if (!out_v.contains(temp_record)) {
			out_v.addElement(temp_record);
			printRecord(temp_record);
			total_up++;
		    }
		}		
	    }

	    if (total_up != 0) {
		MyPrint.printLine("-",100);
		System.out.println("Total UP:"+total_up);
		MyPrint.printLine("-",100);
		total_up = 0;
	    }

	    Enumeration enum3 = inputV2.elements();
	    while ( enum3.hasMoreElements()) {
		temp_record = (StockRecord)enum3.nextElement();
		if ((temp_record.getSectorName()).equals(record1.getSectorName()) &&
		    (!temp_record.getTick().equals("Symbol"))){
		    if (!out_v.contains(temp_record)) {
			out_v.addElement(temp_record);
			printRecord(temp_record);
			total_down++;
		    }
		}		
	    }

	    if (total_down != 0) {
		MyPrint.printLine("-",100);
		System.out.println("Total Down:"+total_down);
		MyPrint.printLine("-",100);
		total_down = 0;
	    }
	}
    }

   private void sumSectorTotal(Vector inputV1, Vector inputV2) {

	int total_up   = 0;
	int total_down = 0;
	Vector out_v   = new Vector ();
	
	Vector s_t_hold_up_v = new Vector ();
	Vector s_t_hold_down_v = new Vector ();

	StockRecord record1     = new StockRecord ();
	StockRecord record2     = new StockRecord ();
	StockRecord temp_record = new StockRecord ();

	double t_m_up      = 0.00;
	double t_m_down    = 0.00;
	double t_price     = 0.00;
	double t_percent   = 0.00;
	double pre_price   = 0.00;
	long   v_up        = 0;
	long   v_down      = 0;
	long   t_v_up      = 0;
	long   t_v_down    = 0;
	double n_m_up      = 0.00;
	double n_m_down    = 0.00;
	long   n_v_up      = 0;
	long   n_v_down    = 0;
	int    n_s_up      = 0;
	int    n_s_down    = 0;
	String temp = null;

	Enumeration enum1 = inputV1.elements();
	while ( enum1.hasMoreElements()) {

	    record1 = (StockRecord)enum1.nextElement();

	    if ((record1.getTick()).equals("Symbol")) {
		MyPrint.printLine("=",100);
		printRecord(record1);
		MyPrint.printLine("=",100);
		continue;
	    }

	    Vector s_t_up_v = new Vector ();
	    Vector s_t_down_v = new Vector ();

	    Enumeration enum2 = inputV1.elements();
	    while ( enum2.hasMoreElements()) {
		temp_record = (StockRecord)enum2.nextElement();
		if ((temp_record.getSectorName()).equals(record1.getSectorName())){

		    if (!out_v.contains(temp_record)) {
			out_v.addElement(temp_record);
			printRecord(temp_record);
			temp = temp_record.getPrice().replaceAll(",","");
			t_price = Double.valueOf(temp).doubleValue();
			temp = (temp_record.getPercent()).replaceAll("%","");
			temp = temp.replaceAll(",","");
			t_percent =
			    0.01 * Double.valueOf(temp).doubleValue();
			temp = temp_record.getVolume().replaceAll(",","");
			v_up = Long.valueOf(temp).longValue();

			t_v_up += v_up;
			t_m_up += v_up * t_percent * t_price/(1+t_percent);
			total_up++;
		    }
		}
		else {
		    continue;
		}		
	    }

	    if (total_up != 0) {
		MyPrint.printLine("-",100);
	    }

	    Enumeration enum3 = inputV2.elements();
	    while ( enum3.hasMoreElements()) {
		temp_record = (StockRecord)enum3.nextElement();
		if ((temp_record.getSectorName()).equals(record1.getSectorName()) &&
		    (!temp_record.getTick().equals("Symbol"))){
		    if (!out_v.contains(temp_record)) {
			out_v.addElement(temp_record);
			printRecord(temp_record);
			t_price   = Double.valueOf(temp_record.getPrice()).doubleValue();
			temp = temp_record.getPercent().replaceAll("%","");
			temp = temp.replaceAll(",","");
			t_percent =
			    0.01 * Double.valueOf(temp).doubleValue();
			v_down = Long.valueOf(temp_record.getVolume().replaceAll(",","")).longValue();
			t_v_down += v_down;
			t_m_down += v_down * t_percent * t_price/(1+t_percent);
			total_down++;
		    }
		}
		else {
		    continue;
		}
	    }

	    if (total_down != 0) {
		MyPrint.printLine("=",100);
	    }

	    if (total_up != 0) {
		s_t_up_v.addElement(record1.getSectorId());
		s_t_up_v.addElement(record1.getSectorName());
		s_t_up_v.addElement(record1.getIndustryId());
		s_t_up_v.addElement(record1.getIndustryName());
		s_t_up_v.addElement(Integer.toString(total_up));
		s_t_up_v.addElement(Long.toString(t_v_up));
		s_t_up_v.addElement(Double.toString(t_m_up));
		s_t_hold_up_v.addElement(s_t_up_v);
	    }

	    if (total_down != 0) {
		s_t_down_v.addElement(record1.getSectorId());
		s_t_down_v.addElement(record1.getSectorName());
		s_t_down_v.addElement(record1.getIndustryId());
		s_t_down_v.addElement(record1.getIndustryName());
		s_t_down_v.addElement(Integer.toString(total_down));
		s_t_down_v.addElement(Long.toString(t_v_down));
		s_t_down_v.addElement(Double.toString(t_m_down));
		s_t_hold_down_v.addElement(s_t_down_v);
	    }

	    n_m_up   += t_m_up;
	    n_m_down += t_m_down;
	    n_v_up   += t_v_up;
	    n_v_down += t_v_down;
	    n_s_up   += total_up;
	    n_s_down += total_down;

	    total_up = 0;
	    t_m_up   = 0.0;
	    t_v_up   = 0;

	    total_down = 0;
	    t_m_down   = 0.00;
	    t_v_down   = 0;

	}
		
	printSectorReport( s_t_hold_up_v, s_t_hold_down_v, 
			  n_s_up, n_s_down, 
			  n_v_up, n_v_down, 
			  n_m_up, n_m_down);
    }


    private void printSectorReport (Vector s_t_h_up_v, Vector s_t_h_down_v, 
				   int t_up, int t_down, 
				   long v_up, long v_down, 
				   double m_up, double m_down) {

	String query_string = null;
	String s_id_up = null;
	String s_id_down = null;
	String s_name_up = null;
	String s_name_down = null;
	String i_id_up = null;
	String i_id_down = null;
	String i_name_up = null;
	String i_name_down = null;
	int s_t_s_up = 0;
	int s_t_s_down = 0;
	long s_t_v_up = 0;
	long s_t_v_down = 0;
	double s_t_$_up = 0.0;
	double s_t_$_down = 0.0;

	Vector sector_up_v = new Vector ();
	Vector sector_down_v = new Vector ();
	String temp = null;

	DateAndTime dt = new DateAndTime ();

	Enumeration enum_up = s_t_h_up_v.elements();

	while (enum_up.hasMoreElements()) {

	    sector_up_v = (Vector)enum_up.nextElement();
	 
	    Enumeration enum_s_up = sector_up_v.elements();

	    s_id_up   =  (String)enum_s_up.nextElement();
	    s_name_up =  (String)enum_s_up.nextElement();
	    i_id_up   =  (String)enum_s_up.nextElement();
	    i_name_up =  (String)enum_s_up.nextElement();
	    s_t_s_up  = Integer.parseInt((String)enum_s_up.nextElement());
	    s_t_v_up  = Long.parseLong((String)enum_s_up.nextElement());
	    s_t_$_up  = Double.parseDouble((String)enum_s_up.nextElement());
	
	    Enumeration enum_down = s_t_h_down_v.elements();

	    boolean found = false ;

	    while (enum_down.hasMoreElements() && !found) {

		sector_down_v = (Vector)enum_down.nextElement();

		Enumeration enum_s_down = sector_down_v.elements();

		while (enum_s_down.hasMoreElements()) {

		    s_id_down   = (String)enum_s_down.nextElement();
		    s_name_down = (String)enum_s_down.nextElement();
		    i_id_down   = (String)enum_s_down.nextElement();
		    i_name_down = (String)enum_s_down.nextElement();

		    if (s_name_down.equals(s_name_up)) {
			s_t_s_down = Integer.parseInt((String)enum_s_down.nextElement());
			s_t_v_down = Long.parseLong((String)enum_s_down.nextElement());
			s_t_$_down = Double.parseDouble((String)enum_s_down.nextElement());
			found = true;
		    }
		    else {
			s_t_s_down = 0;
			s_t_v_down = 0;
			s_t_$_down = 0;
			break;
		    }
		}
	    }

	    MyPrint.printLine ("=",100);
	    System.out.print  ("Sector Id : "+ s_id_up+" ");
	    System.out.print  ("Industry Id : "+ i_id_up+" ");
	    System.out.print  ("Sector Name : "+s_name_up+" ");
	    System.out.println("Industry Name : "+i_name_up);
	    MyPrint.printLine ("=",100);
	    System.out.print  (mf.rightIndent(s_t_s_up, 4, ' ')+" ");
	    System.out.print  (mf.rightIndent(100*s_t_s_up/(s_t_s_up+s_t_s_down), 4, ' ')+"% ");
	    System.out.print  (mf.rightIndent(100*(s_t_s_up)/(t_up+t_down), 4, ' ')+"% ");

	    System.out.print(mf.rightIndent(s_t_v_up,10, ' ')+" ");
	    System.out.print(mf.rightIndent(100*s_t_v_up/(s_t_v_up+s_t_v_down), 4, ' ')+"% ");
	    System.out.print(mf.rightIndent(100*(s_t_v_up)/(v_up+v_down),4,' ')+"%");
	    System.out.print(mf.rightIndent(td.format(s_t_$_up), 20, ' ')+" ");
	    System.out.print(mf.rightIndent(td.format(100*s_t_$_up/(s_t_$_up-s_t_$_down)),8,' ')+"% ");
	    System.out.println(mf.rightIndent(td.format(100*(s_t_$_up)/(m_up-m_down)),10,' ')+"%");
	
	    if( s_t_s_down != 0 ) {
		System.out.print(mf.rightIndent(s_t_s_down, 4, ' ')+" ");
		System.out.print(mf.rightIndent(100*s_t_s_down/(s_t_s_up+s_t_s_down), 4, ' ')+"% ");
		System.out.print(mf.rightIndent(100*(s_t_s_down)/(t_up+t_down), 4, ' ')+"% ");
		System.out.print(mf.rightIndent(s_t_v_down,10, ' ')+" ");
		System.out.print(mf.rightIndent(100*s_t_v_down/(s_t_v_up+s_t_v_down),4,' ')+"% ");
		System.out.print(mf.rightIndent(100*(s_t_v_down)/(v_up+v_down),4,' ')+"%");
		System.out.print(mf.rightIndent(td.format(s_t_$_down),20,' ')+" ");
		System.out.print(mf.rightIndent(td.format(100*s_t_$_down/(s_t_$_down-s_t_$_up)),8,' ')+"% ");
		System.out.println(mf.rightIndent(td.format(100*(s_t_$_down)/(m_down-m_up)),10,' ')+"%");
	    }

	    query_string = "INSERT INTO sector_record VALUES('"+dt.getCurrentDate()+"','"+ 
		dt.getCurrentTime()+"'," +"'"+
		s_id_up     +"','"+
		s_name_up   +"'," +
		(s_t_s_up+s_t_s_down) + "," + 
		s_t_s_up            + "," + 
		s_t_s_down          + "," +
		(s_t_v_up+s_t_v_down) + "," +
		s_t_v_up            + "," + 
		s_t_v_down          + "," +
		(s_t_$_up-s_t_$_down) + "," +
		s_t_$_up            + "," +
		s_t_$_down          + ");";

	    if (save) {
		MyPrint.printLine ("=",100);
		insertIntoDataBase(query_string);
	    }
	}


	MyPrint.printLine("*",100);
	System.out.println("*  Total Stock   Up   : "+t_up+"\t"+100*t_up/(t_up+t_down)+"%");
	System.out.println("*  Total Stock Down   : "+t_down+"\t"+100*t_down/(t_up+t_down)+"%");

	System.out.println("*  Total Stock        : "+(t_up+t_down)+"\t");
	System.out.println("*  --------------------------------------------------------------------------");
	System.out.println("*  Total Money   Up   : $"+
			   td.format(m_up)+"\t"+(td.format(100*m_up/(m_up-m_down)))+"%");
	System.out.println("*  Total Money Down   : $"+
			   td.format(m_down)+"\t"+(td.format(100*m_down/(m_up-m_down)))+"%");
	System.out.println("*  Total Money        : $"+td.format(m_up-m_down));
	System.out.println("*  --------------------------------------------------------------------------");
	System.out.println("*  Total Volume   Up  : "+v_up+
			   "\t"+(td.format(100*v_up/(v_up+v_down)))+"%");
	System.out.println("*  Total Volume Down  : "+v_down+
			   "\t"+(td.format(100*v_down/(v_up+v_down)))+"%");
	System.out.println("*  Total Volume       : "+(v_up+v_down));
	MyPrint.printLine("*",100);

	s_id_up = "0";
	s_name_up = "Total";

	query_string = "INSERT INTO sector_record VALUES('"+dt.getCurrentDate()+"','"+
	    dt.getCurrentTime()+"'," +"'"+
	    s_id_up     +"','"+
	    s_name_up   +"'," +
	    (t_up+t_down) + "," + 
	    t_up            + "," + 
	    t_down          + "," +
	    (v_up+v_down) + "," +
	    v_up            + "," + 
	    v_down          + "," +
	    (m_up-m_down) + "," +
	    m_up            + "," +
	    m_down          + ");";

	if (save) {
	    insertIntoDataBase(query_string);
	}

    }

    private void printRecord(StockRecord input_record) {

	StockRecord record = new StockRecord ();
	record = input_record;

	System.out.print(mf.leftIndent((record.getTick()),6,' ')+" ");
	System.out.print(mf.rightIndent(record.getPrice(),8,' ')+" ");
	System.out.print(mf.rightIndent(record.getPercent(), 8, ' ')+" ");
	System.out.print(mf.rightIndent(record.getVolume(), 12, ' ')+" ");
	System.out.print(mf.rightIndent(record.getMarkCap(), 15, ' ')+" ");
	System.out.print(mf.rightIndent(record.getSectorId(), 5, ' ' )+" ");
	System.out.print(mf.rightIndent(record.getIndustryId(), 5, ' ' )+" ");
	System.out.print(record.getSectorName()+" ");
	System.out.print(record.getIndustryName()+" ");
	System.out.println();
    }

    private void printRecord(Vector inputV) {

	int total = 0;
	StockRecord record = new StockRecord ();

	Enumeration penum = inputV.elements();
	while ( penum.hasMoreElements()) {

	    record = (StockRecord)penum.nextElement();
	    total++;
	    //System.out.print(record.getTime());
	    System.out.print(mf.rightIndent((record.getTick()),6,' ')+" ");
	    //System.out.print(record.getName()+"\t");
	    System.out.print(mf.rightIndent(record.getPrice(),6,' ')+" ");
	    //System.out.print(record.getChange()+"\t");
	    System.out.print(mf.rightIndent(record.getPercent(), 8, ' ')+" ");
	    System.out.print(mf.rightIndent(record.getVolume(), 12, ' ')+" ");
	    //System.out.print(record.getHigh()+"\t");
	    //System.out.print(record.getLow()+"\t");
	    //System.out.print(record.getPeratio()+"\t");
	    System.out.print(mf.rightIndent(record.getMarkCap(), 15, ' ')+" ");
	    //System.out.print(record.getUrl()+"\t");
	    System.out.print(mf.rightIndent(record.getSectorId(), 5, ' ' )+" ");
	    System.out.print(record.getSectorName()+"\t");
	    System.out.println();
	}

	if (total!=0) {
	    MyPrint.printLine("-",100);
	    System.out.println("Total:  "+ total);
	    MyPrint.printLine("=",100);
	}
    }

    private void printTickList(Vector inputV) {

	StockRecord record = new StockRecord ();

	Enumeration penum = inputV.elements();
	while ( penum.hasMoreElements()) {
	    record = (StockRecord)penum.nextElement();
	    System.out.print(record.getTick());
	    System.out.println();
	}
    }

    private void saveRecordIntoDataBase( Vector inputV) {
	Calendar calendar = Calendar.getInstance();

	String date = (calendar.get(Calendar.MONTH)+1)+"/"+
	       calendar.get(Calendar.DATE)+"/" +
	       calendar.get(Calendar.YEAR);
	StockRecord record = new StockRecord ();

	Enumeration penum = inputV.elements();
	while ( penum.hasMoreElements()) {
	    record = (StockRecord)penum.nextElement();
	    if (!(record.getTick()).equals("Symbol")) {
		StringBuffer queryBuffer = new StringBuffer();
		queryBuffer.append("'" +date                       +"',"+
			   "'" +record.getTime()           +"',"+
			   "'" +record.getTick() +"',"+
			   "'" +record.getName()           +"',"+
			   "'" +record.getPrice()          +"',"+ 
			   "'" +record.getChange()+"',"+
			   "'" +record.getPercent() +"',"+ 
			   "'" +record.getVolume()        +"',"+
			   "'" +record.getHigh()    +"',"+ 
			   "'" +record.getLow()    +"',"+ 
			   "'" +record.getPeratio()    +"',"+ 
			   "'" +record.getMarkCap()    +"',"+ 
			   "'" +"n/a"+record.getUrl()    +"',"+ 
			   "'" +record.getSectorId()    +"',"+ 
			   "'" +record.getSectorName() +"'" );

		queryString = queryBuffer.toString();
		insertIntoDataBase(queryString);
		
		//System.out.println(queryString);
	    }
	}
    }
    
    private void insertIntoDataBase( String query_string) {
	System.out.println(query_string);
	DataBaseInsert myInsert = new DataBaseInsert();	
	myInsert.setQueryString(query_string);
	myInsert.insertData();
    }            
}






